
package nuffzone;

import java.util.*;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.FetchOptions;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.users.User;

public class noteManager {
	private static final noteManager instance = new noteManager();
	private static final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
	
	
		private noteManager(){
		}
		
		public static noteManager getInstance() {
			return instance;
		}
		
		public void createNote(String username, String noteText, String priority, String id) {
			
			Entity note = null;

			note = new Entity("Note");
			note.setProperty("Name", username);
			note.setProperty("Text", noteText);
			note.setProperty("Priority", priority);
			note.setProperty("Id", id);
				datastore.put(note);
		}
		
		public void deleteNote(String username, String id){
			Query notesQuery = new Query("Note");
			List<Entity> results = datastore.prepare(notesQuery).asList(
				    FetchOptions.Builder.withDefaults());
			boolean done = false;
			for(Entity e : results){
				if(!done){
					String MUsername = (String) e.getProperty("Name");
					String MId = (String) e.getProperty("Id");
					if(MUsername.equals(username) && MId.equals(id)){
						System.out.println("deleting: "+MId);
						datastore.delete(e.getKey());
						done = true;
					}
				}
			}
		}
		
		public ArrayList<Note> getAllNotesAsList(){
			
			ArrayList<Note> noteList = new ArrayList<Note>();
			
			Query notesQuery = new Query("Note");
			List<Entity> results = datastore.prepare(notesQuery).asList(
				    FetchOptions.Builder.withDefaults());
			for(Entity e : results)
			{
				String MUsername = (String) e.getProperty("Name");
				String MText = (String) e.getProperty("Text");
				String MPriority = (String) e.getProperty("Priority");
				String MId = (String) e.getProperty("Id");
				Note m = new Note(MUsername, MText, MPriority, MId);
				noteList.add(m);
			}
			return noteList;
		}
		
		public ArrayList<Note> getAllNotesAsListFromUser(User currentUser){
			
			ArrayList<Note> noteList = new ArrayList<Note>();
			String username = currentUser.getNickname();
			
			Query notesQuery = new Query("Note");
			List<Entity> results = datastore.prepare(notesQuery).asList(
				    FetchOptions.Builder.withDefaults());
			
			for(Entity e : results)
			{
				String MUsername = (String) e.getProperty("Name");
				
				if(MUsername.equals(username)){
				String MText = (String) e.getProperty("Text");
				String MPriority = (String) e.getProperty("Priority");
				String MId = (String) e.getProperty("Id");
				Note m = new Note(MUsername, MText, MPriority, MId);
				
				noteList.add(m);
				}
			}
			return noteList;
		}
}